<template>
  <view class="chat-container">
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <template v-slot:content>平台客服</template>
    </cu-custom>
    <view class="cu-chat" id="chat-list">
      <view
        v-for="(msg, idx) in messages"
        :key="idx"
        class="cu-item"
        :class="{ self: msg.self }"
      >
        <view
          class="cu-avatar"
          :style="
            'background-image:url(' + (msg.self ? userAvatar : kefuAvatar) + ')'
          "
        ></view>
        <view class="main">
          <view class="bubble-wrap" :class="msg.self ? 'user' : 'kefu'">
            <view
              class="bubble"
              :class="msg.self ? 'user-bubble' : 'kefu-bubble'"
            >
              {{ msg.content }}
            </view>
            <view
              class="bubble-arrow"
              :class="msg.self ? 'user-arrow' : 'kefu-arrow'"
            ></view>
          </view>
        </view>
      </view>
    </view>
    <view class="chat-input-bar">
      <input
        v-model="inputText"
        class="chat-input"
        placeholder="请输入内容..."
        :maxlength="200"
      />
      <button class="cu-btn send-btn" @click="sendMsg">发送</button>
    </view>
  </view>
</template>

<script setup>
import { ref, nextTick } from "vue";
import { post } from "@/utils/request.js";

const inputText = ref("");
const kefuAvatar = "/static/images/kefu.png";
let user = uni.getStorageSync("user");
if (typeof user === "string") {
  try {
    user = JSON.parse(user);
  } catch (e) {
    user = {};
  }
}
const userAvatar = user?.avatar || "/static/logo.png";

const messages = ref([{ content: "您好，有什么可以帮您？", self: false }]);

const scrollToBottom = () => {
  nextTick(() => {
    const el = document.getElementById("chat-list");
    if (el) el.scrollTop = el.scrollHeight;
  });
};

const sendMsg = async () => {
  if (!inputText.value) {
    uni.showToast({ title: "请输入内容", icon: "none" });
    return;
  }
  let user = uni.getStorageSync("user");
  if (typeof user === "string") {
    try {
      user = JSON.parse(user);
    } catch (e) {
      user = {};
    }
  }
  const userId = user?.userId || "";
  try {
    uni.showLoading({ title: "发送中..." });
    console.log("发送的消息是：" + inputText.value + ", 用户ID：" + userId);
    const res = await post("/chat/send", { userId, content: inputText.value });
    uni.hideLoading();
    if (res.data && (res.data.code === 200 || res.statusCode === 200)) {
      messages.value.push({ content: inputText.value, self: true });
      inputText.value = "";
      scrollToBottom();
      uni.showToast({ title: "发送成功", icon: "success" });
    } else {
      uni.showToast({ title: res.data?.msg || "发送失败", icon: "none" });
    }
  } catch (err) {
    uni.hideLoading();
    uni.showToast({ title: err.message || "发送失败", icon: "none" });
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(180deg, #f8f8f8 60%, #eaf3ff 100%);
}
.cu-chat {
  flex: 1;
  padding: 40rpx 24rpx 20rpx 24rpx;
  overflow-y: auto;
  width: 100%;
  display: flex;
  flex-direction: column;
}
.cu-item {
  display: flex;
  align-items: flex-end;
  margin-bottom: 32rpx;
  width: 100%;
}
.cu-avatar {
  width: 72rpx;
  height: 72rpx;
  border-radius: 50%;
  background-size: cover;
  background-position: center;
  margin: 0 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}
.main {
  display: flex;
  align-items: flex-end;
  width: 100%;
}
.bubble-wrap {
  display: flex;
  align-items: flex-end;
  position: relative;
  max-width: 80%;
  width: auto;
}
.kefu .bubble-wrap {
  justify-content: flex-start;
}
.user .bubble-wrap {
  justify-content: flex-end;
  margin-left: auto;
}
.bubble {
  padding: 22rpx 32rpx;
  font-size: 32rpx;
  max-width: 480rpx;
  border-radius: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  word-break: break-all;
  position: relative;
}
.kefu-bubble {
  background: linear-gradient(135deg, #eaf3ff 60%, #b2d6ff 100%);
  color: #222;
  border-radius: 24rpx 24rpx 24rpx 8rpx;
}
.user-bubble {
  background: linear-gradient(135deg, #4f8cff 60%, #1e62d0 100%);
  color: #fff;
  border-radius: 24rpx 24rpx 8rpx 24rpx;
}
.bubble-arrow {
  width: 0;
  height: 0;
  border-style: solid;
  position: absolute;
  bottom: 12rpx;
}
.kefu .bubble-arrow {
  left: -16rpx;
  border-width: 12rpx 16rpx 12rpx 0;
  border-color: transparent #eaf3ff transparent transparent;
}
.user .bubble-arrow {
  right: -16rpx;
  border-width: 12rpx 0 12rpx 16rpx;
  border-color: transparent transparent transparent #4f8cff;
}
.self {
  flex-direction: row-reverse;
  justify-content: flex-end;
}
.self .main {
  flex-direction: row-reverse;
}
.self .bubble-wrap {
  flex-direction: row-reverse;
  margin-left: auto;
}
.chat-input-bar {
  display: flex;
  align-items: center;
  padding: 24rpx 24rpx 36rpx 24rpx;
  background: #fff;
  border-top: 1px solid #e6e6e6;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.03);
}
.chat-input {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 40rpx;
  padding: 0 32rpx;
  font-size: 34rpx;
  background: #f5f7fa;
  margin-right: 20rpx;
  outline: none;
  box-sizing: border-box;
  line-height: 80rpx;
  color: #222;
  transition: box-shadow 0.2s;
}
.chat-input:focus {
  box-shadow: 0 0 0 2rpx #b2d6ff;
}
.send-btn {
  min-width: 120rpx;
  height: 80rpx;
  border-radius: 40rpx;
  background: linear-gradient(90deg, #4f8cff 0%, #1e62d0 100%);
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  box-shadow: 0 2rpx 8rpx rgba(79, 140, 255, 0.12);
  border: none;
  transition: background 0.2s;
}
.send-btn:active {
  background: #1e62d0;
}
</style>
